/**
 * 
 */
package org.statewalker.core.server;

import java.util.Map;

import org.statewalker.core.DelegateState;
import org.statewalker.core.IEvent;
import org.statewalker.core.IState;

/**
 * This class produces state handlers tracing method calls.
 * 
 * @author kotelnikov
 */
public class WrappedClassBasedStateFactory extends ClassBasedStateFactory {

    public WrappedClassBasedStateFactory(
        Class<? extends IState> cls,
        Map<String, String> properties)
        throws SecurityException,
        NoSuchMethodException {
        super(cls, properties);
    }

    @Override
    public IState newState(String stateKey) {
        IState state = super.newState(stateKey);
        return new DelegateState(state) {
            @Override
            public void activate(IEvent event, ICallback callback) {
                String stateKey = getKey();
                String eventKey = event.getKey();
                println(this, "<"
                    + stateKey
                    + " event='"
                    + eventKey
                    + "' "
                    + "thread='"
                    + Thread.currentThread()
                    + "'>");
                super.activate(event, callback);
            }

            @Override
            public void deactivate(IEvent event, ICallback callback) {
                String stateKey = getKey();
                println(this, "</" + stateKey + ">");
                super.deactivate(event, callback);
            }

            protected void println(IState state, String string) {
                WrappedClassBasedStateFactory.this.println(state, string);
            }
        };
    }

    protected void println(IState state, String string) {
        IState parent = state.getParent();
        while (parent != null) {
            System.out.print("    ");
            parent = parent.getParent();
        }
        System.out.println(string);
    }

}